﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Drawing;
using UMC.Net;
using System.Net.WebSockets;
using UMC.Data;
using System.ComponentModel.DataAnnotations;
using UMC.Security;

namespace UMC.Web
{


    public class WebResource
    {

        public const string ImageResource = "/images/";

        public const string UserResources = "/UserResources/";
        static WebResource _Instance;
        public static void Instance(WebResource webResource, Provider provider)
        {
            webResource._Provider = provider;
            _Instance = webResource;
        }
        public virtual void Remember(String root, Identity identity, string password)
        {

        }
        UMC.Data.Provider _Provider;
        public UMC.Data.Provider Provider
        {
            get
            {
          
                return _Provider;
            }
        }
        public static WebResource Instance()
        {
            if (_Instance == null)
            {
                _Instance = new WebResource();
            }
            return _Instance;
        }
        public virtual string WebDomain()
        {
            return this.Provider["domain"] ?? "localhost";
        }

        public virtual string ImageResolve(Uri uri, object id, object key, object size)
        {
            return ImageResolve(uri, id, key, size, "");
        }
        public virtual string ImageResolve(Uri uri, object id, object key, object size, string cache)
        {
            var AbsolutePath = ImageResolve(id.ToString(), key, size, cache);
            if (AbsolutePath.StartsWith("http://") || AbsolutePath.StartsWith("https://"))
            {
                return AbsolutePath;
            }
            else
            {
                return $"{uri.Scheme}://{uri.Authority}{AbsolutePath}";
            }
        }
        public virtual string ImageResolve(string uri, object size, string cache)
        {
            if (uri.Contains("?"))
            {
                return $"{uri}&umc-image={size}&{cache}";
            }
            else
            {
                return $"{uri}?umc-image={size}&{cache}";
            }
        }
        protected virtual string ImageResolve(string id, object key, object size, string cache)
        {
            var kdey = "";
            switch (size.ToString())
            {
                case "0":
                    return ResolveUrl(String.Format("{2}{0}/{1}/0.png?{3}", id, key, ImageResource, cache));
                case "1":
                    kdey = "m350";
                    break;
                case "2":
                    kdey = "m200";
                    break;
                case "3":
                    kdey = "m150";
                    break;
                case "4":
                    kdey = "m100";
                    break;
                case "5":
                    kdey = "m50";
                    break;
                case "-3":
                    kdey = "m200x140";
                    break;
                case "-1":
                    kdey = "m350x200";
                    break;
                case "-4":
                    kdey = "m400x100";
                    break;
                case "-2":
                    kdey = "m200x100";
                    break;
            }
            return ResolveUrl(String.Format("{2}{0}/{1}/0.png?umc-image={3}&{4}", id, key, ImageResource, kdey, cache));

        }

        public virtual void Transfer(Stream stream, string targetKey)
        {
            if (targetKey.StartsWith("bin/", StringComparison.CurrentCultureIgnoreCase))
            {
                return;
            }
            else if (targetKey.StartsWith("app_data/", StringComparison.CurrentCultureIgnoreCase))
            {
                return;
            }
            else if (targetKey.StartsWith("UserResources/") || targetKey.StartsWith("images/"))
            {
                Utility.Copy(stream, Reflection.ConfigPath("Static/" + targetKey));
            }
            else if (targetKey.IndexOf('.') == -1)
            {
                Utility.Copy(stream, Reflection.ConfigPath("Static/" + targetKey + ".html"));

            }
        }
        public virtual void Transfer(Uri soureUrl, string targetKey)
        {
            if (targetKey.StartsWith("bin/", StringComparison.CurrentCultureIgnoreCase))
            {
                return;
            }
            else if (targetKey.StartsWith("app_data/", StringComparison.CurrentCultureIgnoreCase))
            {
                return;
            }
            switch (soureUrl.Scheme)
            {
                case "file":
                    var file = soureUrl.LocalPath.Replace('/', System.IO.Path.DirectorySeparatorChar);
                    if (System.IO.File.Exists(file))
                    {
                        using (var stream = System.IO.File.OpenRead(file))
                        {
                            Transfer(stream, targetKey.TrimStart('/'));
                        }
                    }
                    break;
                default:
                    soureUrl.WebRequest(new ByteChunk()).Get(xhr =>
                    {
                        xhr.ReadAsStream(stream =>
                        {
                            Transfer(stream, targetKey.TrimStart('/'));
                            stream.Close();
                            stream.Dispose();

                        }, ex => { });

                    });
                    break;
            }

        }

        public virtual string ResolveUrl(Uri uri, string path)
        {
            // UriBuilder
            var AbsolutePath = ResolveUrl(path);
            if (AbsolutePath.StartsWith("http://") || AbsolutePath.StartsWith("https://"))
            {
                return AbsolutePath;
            }
            else
            {
                return $"{uri.Scheme}://{uri.Authority}{AbsolutePath}";
            }
        }

        public virtual string ResolveUrl(string path)
        {
            String vUrl = path;
            if (path.StartsWith("~/"))
            {
                vUrl = path.Substring(1);
            }
            else if (path.StartsWith("~"))
            {
                vUrl = "/" + path.Substring(1);
            }
            return vUrl;
        }
        public virtual void Transfer(Uri uri, object guid, object seq, string type)
        {
            String key = String.Format("images/{0}/{1}/{2}.{3}", guid, seq, 0, type.ToLower());
            Transfer(uri, key);
        }

        public virtual void Transfer(Uri uri, object guid, object seq)
        {
            Transfer(uri, guid, seq, "png");
        }
        public virtual void Push(Uri uri, Guid tid, params object[] objs)
        {
            var str = JSON.Serialize(objs);
            UMC.Host.HttpWebSocket.Send(tid, str);
        }

    }
}
